
package logic.dao;

import java.util.Iterator;
import java.util.List;

import logic.beans.Behavior;
import logic.beans.Drug;
import logic.beans.Food;
import logic.beans.Treatment;

public class TreatmentDAO extends AbstractDBElementDAO<Treatment,Long> {
	public Treatment retrieve(String description) {
		Treatment result = (Treatment)getCurrentSession()
				.createQuery("from Treatment where description = :desc")
				.setParameter("desc",description)
				.uniqueResult();
		
		return result;
	}
	
	@Override
	public void doUpdate(Treatment oldTreatment,Treatment newTreatment) {
		oldTreatment.setDescription(newTreatment.getDescription());
		oldTreatment.setDisease(newTreatment.getDisease());
		oldTreatment.setBehaviors(newTreatment.getBehaviors());
		oldTreatment.setDrugs(newTreatment.getDrugs());
		oldTreatment.setFoods(newTreatment.getFoods());
	}
	
	@Override
	public List<Treatment> retrieveByExample(Treatment exampleInstance,List<String> excludeProperties) {
		List<Treatment> result = super.retrieveByExample(exampleInstance,excludeProperties);
		Iterator<Treatment> resultIt = result.iterator();
		while (resultIt.hasNext()) {
			Treatment eachResult = resultIt.next();
			Iterator<Behavior> exampleBehaviorIt = exampleInstance.behaviorsIterator();
			while (exampleBehaviorIt.hasNext()) {
				if (!eachResult.containsBehavior(exampleBehaviorIt.next())) {
					resultIt.remove();
					break;
				}
			}
		}
		resultIt = result.iterator();
		while (resultIt.hasNext()) {
			Treatment eachResult = resultIt.next();
			Iterator<Drug> exampleDrugIt = exampleInstance.drugsIterator();
			while (exampleDrugIt.hasNext()) {
				if (!eachResult.containsDrug(exampleDrugIt.next())) {
					resultIt.remove();
					break;
				}
			}
		}
		resultIt = result.iterator();
		while (resultIt.hasNext()) {
			Treatment eachResult = resultIt.next();
			Iterator<Food> exampleFoodIt = exampleInstance.foodsIterator();
			while (exampleFoodIt.hasNext()) {
				if (!eachResult.containsFood(exampleFoodIt.next())) {
					resultIt.remove();
					break;
				}
			}
		}
		
		return result;
	}
}
